package com.example.servlet.bookServlet;

import com.example.dao.BookDao;

import com.example.entity.Book;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/bookupdate")
public class BookUpdateServlet extends HttpServlet {
    private BookDao bookDao = new BookDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.doGet(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
//        int idd = Integer.parseInt(request.getParameter("id"));
//        Student id = studentDao.getStudentById(idd);

        try {
            // 获取表单数据
            int id = Integer.parseInt(request.getParameter("id"));
            String name = request.getParameter("name");
            String author = request.getParameter("author");
            String publisher = request.getParameter("publisher");
            int price = Integer.parseInt(request.getParameter("price"));
            System.out.println("书籍表单数据完成");

            // 创建学生对象
            Book book = new Book();
          book.setId(id);
          book.setName(name);
          book.setAuthor(author);
          book.setPublisher(publisher);
          book.setPrice(price);
            System.out.println("学生对象完成");
            // 更新学生信息
            if (bookDao.updateBook(book)) {
                System.out.println("更新成功");
                response.sendRedirect("index.jsp");
            } else {
                request.setAttribute("error", "更新失败");
                request.setAttribute("book", book);
                request.getRequestDispatcher("updatebook.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("index.jsp");
        }
    }
}
